#include <stdlib.h>
#include <stdio.h>

//快速排序
int cmp(const void * a, const void * b)
{
    return *(int *)a - *(int *)b;
}
int latestTimeCatchTheBus(int* buses, int busesSize, int* passengers, int passengersSize, int capacity){
    qsort(buses, busesSize, sizeof (buses[0]), cmp);
    qsort(passengers, passengersSize, sizeof (passengers[0]), cmp);
    int i = 0, j = 0, cap = 0, max = 0, m = 0;
    int ans[capacity];
    for (int i = 0; i < passengersSize && j < busesSize;){
        if (buses[j] >= passengers[i] && cap < capacity) {
            ans[cap++] = passengers[i];
            if (j == busesSize - 1) {
                max = cap;
                m = i;
            }
            i++;
        } else {
            j++;
            cap = 0;
        }
    }
    int min;
    if (max < capacity) {
        min = buses[busesSize -1];
    } else {
        min = ans[max - 1];
    }
    for (int i = m; i >= 0; i--) {
        if (min == passengers[i]) {
            min--;
        }
    }
    return min;
}
int main()
{
    int buses[2] = {10,20}, passengers[4] = {2,17,18,19}, capacity = 2;
    int ret = latestTimeCatchTheBus(buses, 2, passengers, 4, capacity);
    printf("%d", ret);
}